package org.steven.crm.app.api;

import com.steven.sequence.generater.RedisConnectionPool;
import com.steven.sequence.generater.SnowflakeGenerator;
import com.steven.xdb.datasource.ApplicationDataSource;
import com.steven.xweb.config.AppConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.steven.crm.core.cache.RedisCache;
import org.steven.crm.core.service.BaseService;

import java.io.File;
import java.util.Properties;

public class Application {
	private static Logger logger = Logger.getLogger(Application.class);

	private static Application instance = new Application();
	private RedisConnectionPool redisConnectionPool;
	private ApplicationDataSource applicationDataSource;
	private Application(){}
	
	public static Application getInstance() {
		return instance;
	}
	
	public void init() throws Exception {
		logger.info("xweb.env " + AppConfig.getInstance().getRuntimeEnv());

		String configFilePath = AppConfig.getInstance().getApplicationRoot()
				+ File.separator + "WEB-INF" + File.separator + "config";
		Properties appProps = AppConfig.getInstance().getParameterConfig().getProperties();

		applicationDataSource  = new ApplicationDataSource(appProps);
		SnowflakeGenerator.setMachineId(AppConfig.getInstance().getParameterConfig().getParameter("machineID"));
		BaseService.setApplicationDataSource(applicationDataSource);
		
		String logConfigFile = (String) appProps.get("log.configFile");
		if (StringUtils.isNotEmpty(logConfigFile)) {
			PropertyConfigurator.configure(configFilePath + File.separator + logConfigFile);
		}

		redisConnectionPool = new RedisConnectionPool(appProps);
		RedisCache.setPool(redisConnectionPool);
	}

	public RedisConnectionPool getRedisConnectionPool() {
		return redisConnectionPool;
	}

	public ApplicationDataSource getApplicationDataSource() {
		return applicationDataSource;
	}
}
